/*
 * @lc app=leetcode id=21 lang=cpp
 *
 * [21] Merge Two Sorted Lists
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

        if (!l1 || !l2) {
            return l1 ? l1 : l2;
        }

        ListNode *head = NULL, *node = NULL;
        ListNode *n1 = l1, *n2 = l2;
        while (n1 && n2) {
            if (n1->val < n2->val) {
                if (!head) {
                    head = n1;
                    node = head;
                } else {
                    node->next = n1;
                    node = node->next;
                }
                n1 = n1->next;
            } else {
                if (!head) {
                    head = n2;
                    node = head;
                } else {
                    node->next = n2;
                    node = node->next;
                }
                n2 = n2->next;
            }
        }

        if (n1) {
            node->next = n1;
        }
        if (n2) {
            node->next = n2;
        }
        return head;
    }
};

